/*
 * @Author: liuYang codkly@gmail.com
 * @Date: 2023-01-19 16:45:42
 * @LastEditors: liuYang codkly@gmail.com
 * @LastEditTime: 2023-01-20 16:21:30
 * @FilePath: \coding\nest\blog_web\composables\hooks.ts
 * @Description:
 * 暂无备注
 */

import { ElMessage, ElMessageBox } from "element-plus";

import Http from "@/utils/http";

export const useCrud = (options: any) => {
  const defaultOptions: any = {
    dataList: [],
    dataListUrl: "",
    queryForm: {},
    page: 1,
    pageSize: 10,
    total: 0,
    dataListLoading: false,
    server: true, //是否服务端加载
    pageStatus: 0, //0 暂无数据  1到底了  2 加载
  };

  const mergeDefaultOptions = (options: any, props: any): any => {
    for (const key in options) {
      if (!Object.getOwnPropertyDescriptor(props, key)) {
        props[key] = options[key];
      }
    }
    return props;
  };

  // 覆盖默认值
  const state = mergeDefaultOptions(defaultOptions, options);
  const query = async () => {
    if (state.pageStatus != 2) {
      return;
    }
    if (!state.dataListUrl) {
      return;
    }
    state.dataListLoading = true;

    const res: any = await Http.get(
      state.dataListUrl,
      {
        page: state.page,
        pageSize: state.pageSize,
        ...state.queryForm,
      },
      state.server
    );
    state.page++;

    // .then((res: any) => {
    state.dataList = state.dataList.concat(res.data.list);
    state.total = res.data.count;
    // })
    state.dataListLoading = false;
    // 到底了
    if (res.data.list.length < state.pageSize) {
      state.pageStatus = 1;
    } else {
      state.pageStatus = 2;
    }
  };
  // 刷新
  const getDataList = async (server: boolean = true) => {
    state.page = 1;
    state.server = server;
    await query();
  };
  //   下一页
  const nextPageHandle = () => {
    query();
  };
  //   暂时无用
  const setState = (data: any) => {
    const { list, count } = data;
    // console.log('rows========>',data)

    Object.assign(state, {
      dataList: list,
      total: count,
    });
  };

  return { getDataList, setState, nextPageHandle };
};
